#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
RPA框架GUI启动脚本 - 简化版
"""

import sys
import os
import logging
import subprocess

# 配置基本日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("rpa_gui.log"),
        logging.StreamHandler()
    ]
)

log = logging.getLogger("rpa_gui_startup")

# 添加项目父目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
sys.path.insert(0, project_root)
log.info(f"已添加项目根目录到Python路径: {project_root}")

# 主函数
def main():
    log.info("启动RPA框架GUI应用程序")
    
    try:
        log.info("Python版本: %s", sys.version)
        
        # 获取app.py的绝对路径
        app_path = os.path.join(current_dir, "gui", "app.py")
        log.info("app.py路径: %s", app_path)
        
        # 检查app.py是否存在
        if not os.path.exists(app_path):
            log.error(f"找不到app.py文件: {app_path}")
            print(f"错误: 找不到app.py文件")
            return 1
        
        log.info("准备启动RPA框架GUI应用程序...")
        
        # 使用subprocess运行app.py，实时捕获输出
        log.info("使用subprocess执行app.py文件...")
        import time
        
        # 创建一个日志文件用于记录所有输出
        log_file_path = os.path.join(current_dir, "app_run_log.txt")
        with open(log_file_path, "w", encoding="utf-8") as log_file:
            # 写入启动信息
            log_file.write(f"=== RPA框架GUI启动日志 ===\n")
            log_file.write(f"启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
            log_file.write(f"Python版本: {sys.version}\n")
            log_file.write(f"app.py路径: {app_path}\n")
            log_file.write(f"工作目录: {current_dir}\n")
            log_file.write("\n=== 程序输出开始 ===\n")
            
            # 使用subprocess.Popen实时捕获输出
            process = subprocess.Popen(
                [sys.executable, app_path],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                cwd=current_dir,
                bufsize=1  # 行缓冲
            )
            
            # 实时读取并显示标准输出
            log.info("开始读取app.py的输出...")
            for line in process.stdout:
                line = line.strip()
                if line:
                    print(f"[app.py stdout] {line}")
                    log.info(f"app.py输出: {line}")
                    log_file.write(f"stdout: {line}\n")
                    log_file.flush()
            
            # 读取并显示标准错误
            for line in process.stderr:
                line = line.strip()
                if line:
                    print(f"[app.py stderr] {line}")
                    log.warning(f"app.py错误: {line}")
                    log_file.write(f"stderr: {line}\n")
                    log_file.flush()
            
            # 等待进程结束并获取返回码
            return_code = process.wait()
            log_file.write(f"\n=== 程序输出结束 ===\n")
            log_file.write(f"程序返回码: {return_code}\n")
        
        log.info(f"app.py执行完成，返回码: {return_code}")
        log.info(f"详细日志已保存到: {log_file_path}")
        
        return return_code
        
    except Exception as e:
        log.critical(f"应用程序启动失败: {e}")
        import traceback
        log.debug(traceback.format_exc())
        
        # 尝试显示错误消息框
        try:
            from PyQt5.QtWidgets import QApplication, QMessageBox
            error_app = QApplication(sys.argv)
            QMessageBox.critical(
                None, 
                "错误", 
                f"启动RPA框架失败: {str(e)}"
            )
        except:
            print(f"错误: {e}")
        
        # 写入错误日志文件
        with open("gui_error_log.txt", "w", encoding="utf-8") as f:
            f.write(f"错误: {e}\n")
            f.write(traceback.format_exc())
        
        input("按Enter键退出...")
        return 1
    
    finally:
        log.info("RPA框架GUI启动脚本已完成")

if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        log.info("用户中断程序")
        print("程序已中断")
        sys.exit(0)
    except Exception as e:
        log.critical(f"发生严重错误: {e}", exc_info=True)
        print(f"严重错误: {e}")
        import traceback
        traceback.print_exc()
        input("按Enter键退出...")
        sys.exit(1)